'use strict'
const urlJoin = require('url-join')
const axios = require('axios')
const https = require('https')
const semver = require('semver')

function getNpmInfo (npmName, registry) {
  // console.log(npmName, registry)
  if (!npmName) return null
  const registryUrl = registry || getDefaultRegistry()
  const npmInfoUrl = urlJoin(registryUrl, npmName)
  // console.log(npmInfoUrl)
  return axios.get(npmInfoUrl, {
    httpsAgent: new https.Agent({ rejectUnauthorized: false })
  }).then((res) => {
    if (res.status === 200)
      return res.data
  })
}

function getDefaultRegistry (isOriginal = false) {
  return isOriginal ? 'https://registry.npm.taobao.org' : 'https://registry.npmjs.org'
}

function getSemverVersion (currentVersion, versions) {
  const res = versions.filter((v) => {
    return semver.satisfies(v, `>${currentVersion}`)
  }).sort((a, b) => {
    return semver.gt(b, a) ? 1 : -1
  })
  if (res && res.length > 0) {
    return res[0]
  }
}

async function getNpmSemverVersion (currentVersion, npmName) {
  npmName = '@imooc-cli/core'
  let { versions } = await getNpmInfo(npmName)
  const lastVersion = getSemverVersion(currentVersion, Object.keys(versions))
  return lastVersion
}
async function getNpmLatestVersion (npmName, registry) {
  let versions = await getNpmInfo(npmName, registry)
  if (versions) {
    return versions.sort((a, b) => semver.gt(b, a))[versions.length - 1]
  }
  return null
}

module.exports = {
  getNpmInfo,
  getNpmSemverVersion,
  getDefaultRegistry,
  getNpmLatestVersion
}